package com.ljm.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.ljm.entity.RoleEntity;
import com.ljm.entity.UserEntity;
import com.ljm.entity.UserRoleEntity;
import com.ljm.pojo.SecurityUser;
import com.ljm.pojo.User;
import com.ljm.service.RoleService;
import com.ljm.service.UserRoleService;
import com.ljm.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 自定义userDetailsService - 认证用户详情
 * </p>
 *
 * @author qy
 * @since 2019-11-08
 */
@Component
@Slf4j
public  class UserDetailsServiceImpl  implements UserDetailsService {

    @Autowired
    UserService userService;
    @Autowired
    UserRoleService userRoleService;

    @Autowired
    RoleService roleService;
    /***
     * 根据账号获取用户信息
     * @param username:
     * @return: org.springframework.security.core.userdetails.UserDetails
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserEntity user = userService.getOne(new QueryWrapper<UserEntity>().eq("user_login", username));
        if (user==null){
            return null;
        }
        /// 查询用户  查询权限
        List<String> authorities = userService.getUserAuthorityInfo(user.getUserid());
        System.out.println(" List<String> authorities  ===>> "+authorities);
        User user1 = new User();
        user1.setUsername(user.getUserLogin());/// 赋值用户名称  ==  用户登录名
        user1.setPassword(user.getUserPassword()); // 用户密码登录
         /// user1.setToken();  用户token  看自己需要设置
        SecurityUser securityUser = new SecurityUser();
        securityUser.setPermissionValueList(authorities);
        securityUser.setCurrentUserInfo(user1);
        System.out.println("securityUser  ===>> "+securityUser);
        return securityUser;
    }


//    public List<GrantedAuthority> getUserAuthority(Long userId) {
//        // 通过内置的工具类，把权限字符串封装成GrantedAuthority列表
//        return  AuthorityUtils.commaSeparatedStringToAuthorityList(userService.getUserAuthorityInfo(userId));



}